<?php

class Model {

    protected $db = null;
    protected $table;
    protected $primary;
    protected $columns = array();

    function __construct($id = 'id')
    {
	$this->db = DB::connect();
	$this->table = static::get_table_name();
	$this->primary = $id;
    }

    function load($load_id)
    {
	$query = $this->db->prepare('SELECT * FROM `' . $this->table . '` WHERE `' . $this->primary . '` = :load_id ');
	$query->execute(array(':load_id' => $load_id));
	$result = $query->fetch(PDO::FETCH_ASSOC);
	if(!$result)
	    return false;
	foreach ($this->columns as $column)
	{
	    $set = 'set_' . $column;
	    $this->{$set}($result[$column]);
	}
	return true;
    }

    static function get_table_name()
    {
	return strtolower(str_replace('_Model', '', get_called_class()));
    }

    static function count()
    {
	$db = DB::connect();
	$table = static::get_table_name();
	$query = $db->query("SELECT COUNT(*) FROM `" . $table . "`");
	$result = $query->fetch(PDO::FETCH_NUM);
	return $result[0];
    }

    static function all()
    {
	$db = DB::connect();
	$table = static::get_table_name();
	$class = get_called_class();
	$query = $db->query('SELECT * FROM `' . $table . '`');
	if (!$query or $query->rowCount() === 0)
	    return false;
	$loaded_class_array = array();
	while ($result = $query->fetch(PDO::FETCH_ASSOC))
	{
	    $loaded_class = new $class();
	    foreach ($loaded_class->columns as $column)
	    {
		$set = 'set_' . $column;
		$loaded_class->{$set}($result[$column]);
	    }
	    $loaded_class_array[] = $loaded_class;
	}
	return $loaded_class_array;
    }

    function to_string()
    {
	foreach ($this->columns as $column)
	{
	    echo $column . ' = ' . $this->{$column} . ' | ';
	}
    }

}